<template>
  <div class="project-management">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <h1>项目管理</h1>
          <el-button type="primary" @click="editProject">编辑</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="16">
        <div class="project-description">
          <h2>项目描述</h2>
          <p :class="{ expanded: isDescriptionExpanded }">
            {{ isDescriptionExpanded ? projectDescription : truncatedDescription }}
            <el-button type="text" v-if="projectDescription.length > 100" @click="toggleDescription">
              {{ isDescriptionExpanded ? '收起' : '展开' }}
            </el-button>
          </p>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="progress">
          <h2>项目进度</h2>
          <hr />
          <h3>任务列表</h3>
          <el-button type="success" @click="goToCreateTask" class="add-task-btn">发布新任务</el-button>
          <el-table :data="paginatedTasks" stripe style="width: 100%">
            <el-table-column width="50" label="" align="center">
              <template #default="scope">
                <div :class="taskStatusClass(scope.row.status)" class="status-indicator"></div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="任务名" width="450"></el-table-column>
            <el-table-column prop="assignedTo" label="负责人" width="300"></el-table-column>
            <el-table-column prop="dueDate" label="截止日期" width="250">
              <template #default="scope">
                {{ formatDate(scope.row.endTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template #default="scope">
                <el-button type="primary" @click="goToEditTask(scope.row)">编辑</el-button>
                <el-button type="danger" @click="confirmDeleteTask(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="tasks.length"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="handlePageChange"
            class="pagination"
          />
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <h2>任务甘特图</h2>
        <Gantt 
          :data="data" 
          :columnsConfig="columnsConfig" 
          :ganttConfig ="{
            planBeginColumn: 'planBegin',
            planEndColumn: 'planEnd',
            actualityBeginColumn: 'actualityBegin',
            actualityEndColumn: 'actualityEnd'
          }"
        />
      </el-col>
    </el-row>
    <el-dialog  v-model="deleteDialogVisible" title="确认删除" width="500">
      <span>确定要删除这个任务吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click='deleteTask'>
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import Gantt from '@/components/GanttChart.vue'
import { useRouter, useRoute } from 'vue-router'
import { ElButton, ElCol, ElRow, ElTable, ElTableColumn, ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const mode = ref(route.params.id)

const projectDescription = ref('')

const deleteDialogVisible = ref(false)
const taskIdToDelete = ref(null)
const isDescriptionExpanded = ref(false)

const truncatedDescription = computed(() => {
  return projectDescription.value.length > 100 ? projectDescription.value.slice(0, 100) + '...' : projectDescription.value
})

const toggleDescription = () => {
  isDescriptionExpanded.value = !isDescriptionExpanded.value
}

const tasks = ref([])

const sortedTasks = computed(() => {
  return tasks.value.sort((a, b) => {
    if (a.status === '正在进行' && b.status !== '正在进行') {
      return -1
    }
    if (a.status !== '正在进行' && b.status === '正在进行') {
      return 1
    }
    return 0
  })
})

const currentPage = ref(1)
const pageSize = ref(5)

const paginatedTasks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = currentPage.value * pageSize.value
  return sortedTasks.value.slice(start, end)
})

const handlePageChange = (page) => {
  currentPage.value = page
}

const editProject = () => {
  console.log('编辑项目')
  router.push({ name: 'task-management'})
}

//新建任务
const goToCreateTask = () => {
  router.push({ name: 'task-creat', params: { mode: 'create', projectId: mode.value } })
}

//编辑任务
const goToEditTask = (task1) => {
  console.log(task1)
  router.push({ name: 'task-creat', params: { mode: 'edit', projectId: mode.value }, query: { task: JSON.stringify(task1) } })
}

//删除任务
const confirmDeleteTask = (id) => {
  taskIdToDelete.value = id
  deleteDialogVisible.value = true
}

const deleteTask = () => {
  tasks.value = tasks.value.filter(task => task.id !== taskIdToDelete.value)
  deleteDialogVisible.value = false
  ElMessage.success('任务已删除')
}

const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}


const taskStatusClass = (status) => {
  switch (status) {
    case '正在进行':
      return 'status-blue'
    case '已完成':
      return 'status-gray'
    case '超时':
      return 'status-red'
    default:
      return ''
  }
}

const fetchProjectData = async () => {
  try {
    const projectResponse = await axios.get('http://localhost:8080/projects/'+mode.value)
    projectDescription.value = projectResponse.data.description

    const tasksResponse = await axios.get('http://localhost:8080/tasks/project/'+mode.value)
    tasks.value = tasksResponse.data
  } catch (error) {
    console.error('获取项目数据和任务数据失败:', error)
  }
}

onMounted(() => {
  fetchProjectData()
})

const data = ref([
		{
			title: '第一阶段',
			planBegin: '2022-01-01',
			planEnd: '2022-01-09',
			actualityBegin: '2022-01-02',
			actualityEnd: '2022-01-10'
		},
		{
			title: '第二阶段',
			planBegin: '2022-01-09',
			planEnd: '2022-01-15',
			actualityBegin: '2022-01-09',
			actualityEnd: '2022-01-18'
		},
    {
      title: '第三阶段',
			planBegin: '2022-01-15',
			planEnd: '2022-01-22',
			actualityBegin: '2022-01-17',
			actualityEnd: '2022-01-21'
    }
	])
	const columnsConfig = ref([
		{
			label: '事项',
			prop: 'title',
			fixed: 'left',
			align: 'center',
			'min-width': 120
		},
		{
			label: '开始',
			prop: 'planBegin',
			fixed: 'left',
			align: 'center',
			'min-width': 120
		},
		{
			label: '结束',
			prop: 'planEnd',
			fixed: 'left',
			align: 'center',
			'min-width': 120
		}
	])

</script>

<style scoped>
.project-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  h1 {
    margin: 0;
  }
}

h2 {
  text-align: left;
  margin: 0;
  font-size: 1.5em;
  color: #333;
}

h3 {
  text-align: left;
  margin: 20px;
  font-size: 1.5em;
  color: #333;
}

p {
  text-align: left;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
}

p.expanded {
  max-height: none;
}

.project-description {
  margin-bottom: 20px;
}

.tasks {
  margin-bottom: 20px;
}

.add-task-btn {
  margin-bottom: 10px;
}

.el-table .el-table__row--striped:nth-child(odd) {
  background-color: #f9f9f9;
}

.el-table .status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  display: inline-block;
}

.status-blue {
  background-color: blue;
}

.status-gray {
  background-color: gray;
}

.status-red {
  background-color: red;
}

.el-table .el-table__header-wrapper {
  text-align: left;
}

</style>
